package com.block.datapush.service.apipush;

import cn.hutool.core.util.ByteUtil;
import cn.hutool.core.util.HexUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.digest.DigestAlgorithm;
import cn.hutool.crypto.digest.Digester;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IApplicationInfoService;
import com.block.common.service.IMemberCommonService;
import com.block.common.service.LogFactory;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.apipush.utils.HaoYongJieQiUtil;
import com.block.db.entity.ApplicationInfo;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import com.block.db.entity.MerchantDataPushInfo;
import com.block.db.mapper.MerchantDataPushInfoMapper;
import jnr.ffi.annotations.In;
import org.apache.commons.codec.BinaryDecoder;
import org.bouncycastle.jcajce.provider.digest.SHA1;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.web3j.utils.Bytes;
import org.web3j.utils.Strings;

import javax.annotation.Resource;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * 好用借
 */
@Service
public class HaoYongJiePushApiService implements IPushApiService {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    IMemberCommonService memberCommonService;
    @Autowired
    IApplicationInfoService applicationInfoService;
    @Resource
    MerchantDataPushInfoMapper merchantDataPushInfoMapper;

    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        String queryUrl = pushApiKeyParam.getCheckUrl();
        String mobileMd5 = memberSourceInfo.getMobileMd5();
        String city = memberSourceInfo.getCity();

        if (StrUtil.endWith(city, "市")) {
            city = memberSourceInfo.getCity().substring(0, memberSourceInfo.getCity().length() - 1);
        }

        long timestamp = System.currentTimeMillis();

        UUID uuid = UUID.randomUUID();
        String requestId = uuid.toString();
        extJson.put("requestId", requestId);

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("phoneMd5", mobileMd5);
        bizMap.put("requestId", requestId);
        bizMap.put("name", memberSourceInfo.getRealname());
        bizMap.put("sex", memberSourceInfo.getSex() == 1 ? 1 : 0);
        bizMap.put("age", memberSourceInfo.getAge());
        bizMap.put("provinceName", memberSourceInfo.getProvince());
        bizMap.put("cityName", city);
        bizMap.put("loanLimit", HaoYongJieQiUtil.getloan(memberSourceInfo.getLoanAmount()));
        bizMap.put("house", HaoYongJieQiUtil.getHouse(memberSourceInfo.getHouse()));
        bizMap.put("car", HaoYongJieQiUtil.getCar(memberSourceInfo.getCar()));
        bizMap.put("accumulation", HaoYongJieQiUtil.getGjj(memberSourceInfo.getGjj()));
        bizMap.put("socialSecurity", HaoYongJieQiUtil.getSocialInsurance(memberSourceInfo.getShebao()));
        bizMap.put("insurance", HaoYongJieQiUtil.getbaodan(memberSourceInfo.getBaoxian()));
        bizMap.put("occupation", HaoYongJieQiUtil.getjob(memberSourceInfo.getGongzuo()));
        bizMap.put("sesameSeed", HaoYongJieQiUtil.getZhimaScore(memberSourceInfo.getZhima()));
        bizMap.put("creditCard", 0);
        bizMap.put("huabei", HaoYongJieQiUtil.getHuabei(memberSourceInfo.getHuabei()));
        bizMap.put("baitiao", HaoYongJieQiUtil.getBaiTiao(memberSourceInfo.getBaitiao()));
        bizMap.put("overdueSituation", HaoYongJieQiUtil.getyuqi(memberSourceInfo.getYuqi()));


        String password = pushApiKeyParam.getApiSecret();

        byte[] pwd1 = sha1Hash(password.getBytes());
        byte[] pwd2 = sha1Hash(pwd1);
        byte[] aesKey = Arrays.copyOf(pwd2, 16); //

        String params = SecureUtil.aes(aesKey).encryptBase64(JSON.toJSONString(bizMap));

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("partnerId", pushApiKeyParam.getApiCode());
        paramMap.put("timestamp", timestamp);
        paramMap.put("params", params);

        // 对参数进行排序
        List<String> keys = new ArrayList<>(paramMap.keySet());
        Collections.sort(keys);

        // 拼接参数
        StringBuilder paramStr = new StringBuilder();
        for (String key : keys) {
            paramStr.append(key).append("=").append(paramMap.get(key)).append("&");
        }
        paramStr.deleteCharAt(paramStr.length() - 1); // 删除最后一个&符号// 删除最后一个&符号

        // 拼接password并计算MD5
        String sign = paramStr.toString() + pushApiKeyParam.getApiSecret();

        String signMd5 = SecureUtil.md5(sign).toLowerCase();
        paramMap.put("sign", signMd5);

        log.info("【好用借】撞库开始【queryUrl】{}【paramMap】{}【bizMap】{}", queryUrl, JSON.toJSONString(paramMap), JSON.toJSONString(bizMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json;charset=UTF-8")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【好用借】撞库结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");

        pushApiResult.setCode(String.valueOf(code));
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(bizMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "200")) {
            pushApiResult.setPushSuccess(true);
        }
        return pushApiResult;
    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setOrderNo(orderNo);

        String requestUrl = pushApiKeyParam.getRegisterUrl();

        String city = memberSourceInfo.getCity();

        if (StrUtil.endWith(city, "市")) {
            city = memberSourceInfo.getCity().substring(0, memberSourceInfo.getCity().length() - 1);
        }

        long timestamp = System.currentTimeMillis();
        UUID uuid = UUID.randomUUID();
        String requestId = uuid.toString();

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("requestId", requestId);
        bizMap.put("phone", memberSourceInfo.getMobile());
        bizMap.put("name", memberSourceInfo.getRealname());
        bizMap.put("sex", memberSourceInfo.getSex() == 1 ? 1 : 0);
        bizMap.put("age", memberSourceInfo.getAge());
        bizMap.put("provinceName", memberSourceInfo.getProvince());
        bizMap.put("cityName", city);
        bizMap.put("loanLimit", HaoYongJieQiUtil.getloan(memberSourceInfo.getLoanAmount()));
        bizMap.put("house", HaoYongJieQiUtil.getHouse(memberSourceInfo.getHouse()));
        bizMap.put("car", HaoYongJieQiUtil.getCar(memberSourceInfo.getCar()));
        bizMap.put("accumulation", HaoYongJieQiUtil.getGjj(memberSourceInfo.getGjj()));
        bizMap.put("socialSecurity", HaoYongJieQiUtil.getSocialInsurance(memberSourceInfo.getShebao()));
        bizMap.put("insurance", HaoYongJieQiUtil.getbaodan(memberSourceInfo.getBaoxian()));
        bizMap.put("occupation", HaoYongJieQiUtil.getjob(memberSourceInfo.getGongzuo()));
        bizMap.put("sesameSeed", HaoYongJieQiUtil.getZhimaScore(memberSourceInfo.getZhima()));
        bizMap.put("creditCard", 0);
        bizMap.put("huabei", HaoYongJieQiUtil.getHuabei(memberSourceInfo.getHuabei()));
        bizMap.put("baitiao", HaoYongJieQiUtil.getBaiTiao(memberSourceInfo.getBaitiao()));
        bizMap.put("overdueSituation", HaoYongJieQiUtil.getyuqi(memberSourceInfo.getYuqi()));

        ApplicationInfo appInfoByAppCode = applicationInfoService.getAppInfoByAppCode(memberSourceInfo.getAppCode());
        String jumpUrl = StrUtil.format("{}prodList", appInfoByAppCode.getH5Url(), memberSourceInfo.getChannelCode());
        bizMap.put("redirect", jumpUrl);

        String password = pushApiKeyParam.getApiSecret();
        byte[] pwd1 = sha1Hash(password.getBytes());
        byte[] pwd2 = sha1Hash(pwd1);
        byte[] aesKey = Arrays.copyOf(pwd2, 16); //

        String params = SecureUtil.aes(aesKey).encryptBase64(JSON.toJSONString(bizMap));
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("partnerId", pushApiKeyParam.getApiCode());
        paramMap.put("timestamp", timestamp);
        paramMap.put("params", params);

        // 对参数进行排序
        List<String> keys = new ArrayList<>(paramMap.keySet());
        Collections.sort(keys);

        // 拼接参数
        StringBuilder paramStr = new StringBuilder();
        for (String key : keys) {
            paramStr.append(key).append("=").append(paramMap.get(key)).append("&");
        }
        paramStr.deleteCharAt(paramStr.length() - 1); // 删除最后一个&符号// 删除最后一个&符号

        // 拼接password并计算MD5
        String sign = paramStr.toString() + pushApiKeyParam.getApiSecret();
        String signMd5 = SecureUtil.md5(sign).toLowerCase();
        paramMap.put("sign", signMd5);

        log.info("【好用借】导单开始【requestUrl】{}【paramMap】{}【bizMap】{}", requestUrl, JSON.toJSONString(paramMap),JSON.toJSONString(bizMap));
        String result = HttpUtil.createPost(requestUrl)
                .header("Content-Type", "application/json;charset=UTF-8")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【好用借】导单结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");
        String data = resultObject.getString("data");

        pushApiResult.setCode(code + "");
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(bizMap));
        pushApiResult.setResultInfo(result);
        pushApiResult.setOutOrderNo(requestId);

        if (StrUtil.equals(String.valueOf(code), "200")) {
            pushApiResult.setApproveUrl(data);
            pushApiResult.setPushSuccess(true);
            pushApiResult.setSettleFlag(false);
            pushApiResult.setStatus(PushStatusEnum.WAIT_APPROVE.getValue());
            return pushApiResult;
        }

        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        return pushApiResult;
    }

    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();

        JSONObject jsonObject = new JSONObject();
        String requestId = jsonObject.getString("requestId");
        Integer code = jsonObject.getInteger("code");

        noticeParamDTO.setOutOrderNo(requestId);
        noticeParamDTO.setOutFlag(true);

        MerchantDataPushInfo entityByOutOrderNoLock = merchantDataPushInfoMapper.getEntityByOutOrderNoLock(infoId, String.valueOf(requestId));
        noticeParamDTO.setMerchantDataPushInfo(entityByOutOrderNoLock);

        if (StrUtil.equals(String.valueOf(code), "200")){
            noticeParamDTO.setStatus(PushStatusEnum.SUCCESS.getValue());
            noticeParamDTO.setSettleFlag(true);
        }else{
            noticeParamDTO.setStatus(PushStatusEnum.FAILED.getValue());
            noticeParamDTO.setSettleFlag(false);
        }
        return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 200);
        jsonObject.put("msg", "成功");
        return jsonObject;
    }

    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        return null;
    }

    public static byte[] sha1Hash(byte[] input) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-1");
            return digest.digest(input);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

}
